package com.wchen.project.ticket.service;

import com.alibaba.fastjson.JSON;
import com.wchen.project.common.utils.SendMailUtil;
import com.wchen.project.common.utils.SslUtils;
import com.wchen.project.ticket.vo.EmailVO;
import com.wchen.project.ticket.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;

/**
 * @Description :   这个服务还有待完善，如果两个url一个刷到票，另一个没刷到，则会一直发送邮件
 * @author: cww
 * @DateTime: 2019/2/2 15:13
 */
@Service
public class TicketService implements ITicketService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static String start_time_str = "05:57";
    private static String end_time_str = "23:00";
    private static final SimpleDateFormat FORMAT_TIME =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat FORMAT_TIME_MIN =  new SimpleDateFormat("HH:mm");

    //查到车票一轮发送几次邮件 默认 5 次
    private static int count_send =  2;
    //当前邮件发送次数 无需修改
    private static int current_count =  0;
    //查到车票一轮持续时间 默认 10 分钟
    private static long send_cycle = 5 * 60 * 1000;
    //本轮检测到车票的起始时间戳 无需修改
    private static long first_send_time = 0;
    //查询哪一个url
    private static int url_flag = 1;

    @Override
    public void getTicketAndSendMail() {
        URL url;
        int responseCode;
        HttpURLConnection urlConnection = null;
        BufferedReader reader;
        try{
            Date startTime =  FORMAT_TIME_MIN.parse(start_time_str);
            Date now = FORMAT_TIME_MIN.parse(FORMAT_TIME_MIN.format(new Date()));
            Date endTime =  FORMAT_TIME_MIN.parse(end_time_str);
            if (now.before(endTime) && now.after(startTime)){
                logger.info("在时间区间内");
                //忽略Ssl(针对12306)
                SslUtils.ignoreSsl();
                //生成一个URL对象
                if (url_flag == 0) {
                    url = new URL("https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2020-01-21&leftTicketDTO.from_station=XMS&leftTicketDTO.to_station=NES&purpose_codes=ADULT");
                    url_flag = 1;
                } else if (url_flag == 1) {
                    url = new URL("https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2020-01-22&leftTicketDTO.from_station=XMS&leftTicketDTO.to_station=NES&purpose_codes=ADULT");
                    url_flag = 0;
                } else {
                    logger.info("未能匹配到车票查询地址");
                    return;
                }
                try {
                    /**
                     * 这是为了防止12306对同一ip多次访问进行限制
                     * 这里填的ip是暂时有效的，想要获取更多就得自己去找 搜索代理ip
                     */
                    System.getProperties().setProperty("proxySet", "false");
                    System.setProperty("http.proxyHost", "115.239.25.250");
                    System.setProperty("http.proxyPort", "9999");
                    //打开URL
                    urlConnection = (HttpURLConnection) url.openConnection();
                    //伪造一个请求头 一般网页不用，有些网站会看你有没有请求头，比如 12306......
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setRequestProperty("Connection","keep-alive");
                    urlConnection.setRequestProperty("Cache-Control","no-cache");
                    urlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
                    urlConnection.setRequestProperty("Accept","*/*");
                    urlConnection.setRequestProperty("X-Requested-With","XMLHttpRequest");
                    urlConnection.setRequestProperty("If-Modified-Since","0");
                    urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");
                    urlConnection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
                    urlConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
                    urlConnection.setRequestProperty("Cookie","JSESSIONID=16F2E0787A9515BA69C348B148624426; route=6f50b51faa11b987e576cdb301e545c4; BIGipServerotn=1961361674.24610.0000; _jc_save_fromStation=%u53A6%u95E8%2CXMS; _jc_save_toStation=%u5B81%u5FB7%2CNES; _jc_save_toDate=2019-12-26; _jc_save_wfdc_flag=dc; RAIL_EXPIRATION=1577607629519; RAIL_DEVICEID=Kn6whY-ItaEX9OmoAgA2DbJJku4_Vzva1LFM46zWZEIg_QS7oGsB7i1PVSajbPnZpeyYb3X1ft1kkH8v78UkTalSLyBEoqxWe8pSf6hIMjICzkFko4RU7OYRieplSOgoxMx_W1MKNytEDVsOuvUtqp6Gz5wH0PoN; BIGipServerpassport=954728714.50215.0000; _jc_save_fromDate=2020-01-22");
                    urlConnection.setRequestProperty("Host","kyfw.12306.cn");
                } catch (Exception e) {
                    logger.error("Http 请求异常：",e);
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                }

                //获取服务器响应代码
                responseCode = urlConnection.getResponseCode();
                logger.info("请求返回状态 responseCode："+responseCode);
                //假如响应代码为200，就是代表成功
                if(responseCode == 200){
                    // 读取返回内容
                    StringBuffer buffer = new StringBuffer();
                    InputStream stream = new GZIPInputStream(urlConnection.getInputStream());
                    reader = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
                    String temp;
                    while ((temp = reader.readLine()) != null) {
                        buffer.append(temp);
                        buffer.append("\n");
                    }
//                    logger.info("buffer:" + buffer);
                    if (!buffer.toString().isEmpty()){
//                        logger.info("请求返回原数据 :"+ buffer);
                        ResultVO resultVO ;
                        resultVO = JSON.parseObject(buffer.toString(), ResultVO.class);
                        boolean isSendEmail = false;
                        StringBuilder stringBuilder = new StringBuilder();
                        if (url_flag == 0) {
                            stringBuilder.append("2020-01-21" + "<br>");
                        } else if (url_flag == 1) {
                            stringBuilder.append("2020-01-22" + "<br>");
                        }
                        for (String resultStr:resultVO.getData().getResult()){
                            List<String> strings = Arrays.asList(resultStr.split("\\|"));
                            if ("D3112".equals(strings.get(3))){
//                                if ((!"无".equals(strings.get(26)))||(!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31)))){
                                if ((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31)))){
                                    stringBuilder.append("D3112：15:16-17:31 02:15"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
                                    logger.info("D3112 刷到余票");
                                    logger.info("D3112：15:16-17:31 02:15");
                                    logger.info("无座："+strings.get(26));
                                    logger.info("二等座："+strings.get(30));
                                    logger.info("一等座："+strings.get(31));
                                    isSendEmail = true;
                                }
                            } else if("D3308".equals(strings.get(3))){
//                                if ((!"无".equals(strings.get(26)))||(!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31)))){
                                if ((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31)))){
                                    stringBuilder.append("D3308：15:41-17:48 02:07"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
                                    logger.info("D3308 刷到余票");
                                    logger.info("D3308：15:41-17:48 02:07");
                                    logger.info("无座："+strings.get(26));
                                    logger.info("二等座："+strings.get(30));
                                    logger.info("一等座："+strings.get(31));
                                    isSendEmail = true;
                                }
                            } else if("D3108".equals(strings.get(3))){
//                                if ((!"无".equals(strings.get(26)))||(!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31)))){
                                if ((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31)))){
                                    stringBuilder.append("D3108：15:41-17:48 02:07"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
                                    logger.info("D3108 刷到余票");
                                    logger.info("D3108：14:32-16:51 02:19");
                                    logger.info("无座："+strings.get(26));
                                    logger.info("二等座："+strings.get(30));
                                    logger.info("一等座："+strings.get(31));
                                    isSendEmail = true;
                                }
                            }
// else if("D3215".equals(strings.get(3))){
//                                if ((!"无".equals(strings.get(26)))||(!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31)))){
//                                    stringBuilder.append("D3215：17:35-19:53 02:18"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
//                                    logger.info("D3215 刷到余票");
//                                    logger.info("D3215：17:35-19:53 02:18");
//                                    logger.info("无座："+strings.get(26));
//                                    logger.info("二等座："+strings.get(30));
//                                    logger.info("一等座："+strings.get(31));
//                                    isSendEmail = true;
//                                }
//                            } else if("D9611".equals(strings.get(3))){
//                                if (((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31))))){
//                                    stringBuilder.append("D9611：16:04-19:28 03:24"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
//                                    logger.info("D9611 刷到余票");
//                                    logger.info("D9611：16:04-19:28 03:24");
//                                    logger.info("无座："+strings.get(26));
//                                    logger.info("二等座："+strings.get(30));
//                                    logger.info("一等座："+strings.get(31));
//                                    isSendEmail = true;
//                                }
//                            }else if("D3131".equals(strings.get(3))){
//                                if (((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31))))){
//                                    stringBuilder.append("D3131：13:07-15:22 02:15"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
//                                    logger.info("D3131 刷到余票");
//                                    logger.info("D3131：13:07-15:22 02:15");
//                                    logger.info("无座："+strings.get(26));
//                                    logger.info("二等座："+strings.get(30));
//                                    logger.info("一等座："+strings.get(31));
//                                    isSendEmail = true;
//                                }
//                            }else if("D2305".equals(strings.get(3))){
//                                if (((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31))))){
//                                    stringBuilder.append("D2305：13:25-15:32 02:07"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
//                                    logger.info("D2305 刷到余票");
//                                    logger.info("D2305：13:25-15:32 02:07");
//                                    logger.info("无座："+strings.get(26));
//                                    logger.info("二等座："+strings.get(30));
//                                    logger.info("一等座："+strings.get(31));
//                                    isSendEmail = true;
//                                }else if("D3295".equals(strings.get(3))){
//                                    if (((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31))))){
//                                        stringBuilder.append("D3295：14:18-16:39 02:21"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
//                                        logger.info("D3295 刷到余票");
//                                        logger.info("D3295：14:18-16:39 02:21");
//                                        logger.info("无座："+strings.get(26));
//                                        logger.info("二等座："+strings.get(30));
//                                        logger.info("一等座："+strings.get(31));
//                                        isSendEmail = true;
//                                    }
//                                }else if("D2285".equals(strings.get(3))){
//                                    if (((!"无".equals(strings.get(30)))||(!"无".equals(strings.get(31))))){
//                                        stringBuilder.append("D2285：14:52-16:59 02:07"+"<br>"+"无座："+strings.get(26)+"<br>"+"二等座："+strings.get(30)+"<br>"+"一等座："+strings.get(31)+"<br>");
//                                        logger.info("D2285 刷到余票");
//                                        logger.info("D2285：14:52-16:59 02:07");
//                                        logger.info("无座："+strings.get(26));
//                                        logger.info("二等座："+strings.get(30));
//                                        logger.info("一等座："+strings.get(31));
//                                        isSendEmail = true;
//                                    }
//                                }
//                            }
                        }
                        Date date = new Date();
                        long timeDifference = (date.getTime() - first_send_time);
                        if (isSendEmail){
                            if ((current_count == 0 || timeDifference < send_cycle) && current_count < count_send) {
                                logger.info("当前发送邮件次数：" + current_count);
                                if (current_count == 0) {
                                    timeDifference = 0;
                                    first_send_time = date.getTime();
                                }
                                logger.info("刷到相关余票 时间："+ FORMAT_TIME.format(date));
                                EmailVO emailVO = new EmailVO();
                                emailVO.setEmailAddress("294147287@qq.com");
                                emailVO.setEmailSubject("刷到余票");
                                emailVO.setEmailContent(stringBuilder.toString());
                                SendMailUtil sendMailTest = new SendMailUtil();
                                sendMailTest.SendMail(emailVO);
                                emailVO.setEmailAddress("294147287@qq.com");
                                sendMailTest.SendMail(emailVO);
                                current_count++;
                            } else {
                                logger.info("本次刷到相关余票但不发送邮件");
                            }
                        } else {
                            current_count = 0;
                            logger.info("本次未刷到相关余票 时间："+ FORMAT_TIME.format(date));
                        }
                        if (current_count > 0 && timeDifference >= send_cycle) {
                            current_count = 0;
                        }
                    }
                }else{
//                    current_count = 0;
                    logger.info("获取不到网页的源码，服务器响应代码为"+ responseCode);
                }
            }else {
                current_count = 0;
                System.out.println("不在时间区间内");
            }

        }catch(Exception e){
            logger.info("获取不到网页的源码，服务器响应代码为 e:"+ e);
        }
    }
}
